"""
WebDriver工厂类，用于创建和管理WebDriver实例
"""
import os
import logging
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.firefox.service import Service as FirefoxService
from selenium.webdriver.edge.service import Service as EdgeService
from tests.config.config import BROWSER, IMPLICIT_WAIT, HEADLESS


class DriverFactory:
    """WebDriver工厂类，负责创建和管理WebDriver实例"""

    @staticmethod
    def get_driver():
        """
        根据配置创建WebDriver实例
        
        Returns:
            WebDriver: 配置好的WebDriver实例
        """
        browser = BROWSER.lower()
        logging.info(f"初始化 {browser} 浏览器")

        # 用户手动下载的WebDriver路径
        user_chrome_driver_path = r"D:\chromedriver\chromedriver.exe"
        
        # 获取项目根目录
        root_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        # drivers目录用于存放WebDriver可执行文件
        drivers_dir = os.path.join(root_dir, "drivers")
        
        if not os.path.exists(drivers_dir):
            os.makedirs(drivers_dir)
            logging.info(f"创建drivers目录: {drivers_dir}")

        if browser == "chrome":
            options = webdriver.ChromeOptions()
            if HEADLESS:
                options.add_argument("--headless=new")
            options.add_argument("--start-maximized")
            options.add_argument("--disable-extensions")
            options.add_argument("--disable-gpu")
            options.add_argument("--no-sandbox")
            options.add_argument("--disable-dev-shm-usage")
            
            # 优先使用用户指定的ChromeDriver路径
            if os.path.exists(user_chrome_driver_path):
                logging.info(f"使用用户指定的ChromeDriver: {user_chrome_driver_path}")
                service = ChromeService(executable_path=user_chrome_driver_path)
                driver = webdriver.Chrome(service=service, options=options)
            # 其次尝试使用项目drivers目录中的ChromeDriver
            elif os.path.exists(os.path.join(drivers_dir, "chromedriver.exe")):
                chrome_driver_path = os.path.join(drivers_dir, "chromedriver.exe")
                logging.info(f"使用项目目录中的ChromeDriver: {chrome_driver_path}")
                service = ChromeService(executable_path=chrome_driver_path)
                driver = webdriver.Chrome(service=service, options=options)
            # 最后使用自动管理
            else:
                logging.info("使用自动管理的ChromeDriver")
                driver = webdriver.Chrome(options=options)
        
        elif browser == "firefox":
            options = webdriver.FirefoxOptions()
            if HEADLESS:
                options.add_argument("--headless")
            
            # 尝试使用本地GeckoDriver
            firefox_driver_path = os.path.join(drivers_dir, "geckodriver.exe")
            
            if os.path.exists(firefox_driver_path):
                logging.info(f"使用本地GeckoDriver: {firefox_driver_path}")
                service = FirefoxService(executable_path=firefox_driver_path)
                driver = webdriver.Firefox(service=service, options=options)
            else:
                logging.warning(f"本地GeckoDriver不存在: {firefox_driver_path}，使用自动管理")
                driver = webdriver.Firefox(options=options)
        
        elif browser == "edge":
            options = webdriver.EdgeOptions()
            if HEADLESS:
                options.add_argument("--headless")
            options.add_argument("--start-maximized")
            
            # 尝试使用本地EdgeDriver
            edge_driver_path = os.path.join(drivers_dir, "msedgedriver.exe")
            
            if os.path.exists(edge_driver_path):
                logging.info(f"使用本地EdgeDriver: {edge_driver_path}")
                service = EdgeService(executable_path=edge_driver_path)
                driver = webdriver.Edge(service=service, options=options)
            else:
                logging.warning(f"本地EdgeDriver不存在: {edge_driver_path}，使用自动管理")
                driver = webdriver.Edge(options=options)
        
        else:
            raise Exception(f"不支持的浏览器类型: {browser}")
        
        driver.implicitly_wait(IMPLICIT_WAIT)
        return driver
        
    @staticmethod
    def create_driver(browser_type=None, options=None):
        """
        创建WebDriver实例，支持传入浏览器类型和选项
        
        Args:
            browser_type (str): 浏览器类型，如'chrome', 'firefox', 'edge'
            options: 浏览器选项对象
            
        Returns:
            WebDriver: 配置好的WebDriver实例
        """
        # 如果未指定浏览器类型，使用配置文件中的默认值
        browser = (browser_type or BROWSER).lower()
        logging.info(f"创建 {browser} 浏览器实例")
        
        # 用户手动下载的WebDriver路径
        user_chrome_driver_path = r"D:\chromedriver\chromedriver.exe"
        
        # 获取项目根目录
        root_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        # drivers目录用于存放WebDriver可执行文件
        drivers_dir = os.path.join(root_dir, "drivers")
        
        if not os.path.exists(drivers_dir):
            os.makedirs(drivers_dir)
            logging.info(f"创建drivers目录: {drivers_dir}")
        
        driver = None
        
        if browser == "chrome":
            # 如果没有传入选项，创建默认选项
            if options is None:
                options = webdriver.ChromeOptions()
                if HEADLESS:
                    options.add_argument("--headless=new")
                options.add_argument("--start-maximized")
                options.add_argument("--disable-extensions")
                options.add_argument("--disable-gpu")
                options.add_argument("--no-sandbox")
                options.add_argument("--disable-dev-shm-usage")
            
            # 优先使用用户指定的ChromeDriver路径
            if os.path.exists(user_chrome_driver_path):
                logging.info(f"使用用户指定的ChromeDriver: {user_chrome_driver_path}")
                service = ChromeService(executable_path=user_chrome_driver_path)
                driver = webdriver.Chrome(service=service, options=options)
            # 其次尝试使用项目drivers目录中的ChromeDriver
            elif os.path.exists(os.path.join(drivers_dir, "chromedriver.exe")):
                chrome_driver_path = os.path.join(drivers_dir, "chromedriver.exe")
                logging.info(f"使用项目目录中的ChromeDriver: {chrome_driver_path}")
                service = ChromeService(executable_path=chrome_driver_path)
                driver = webdriver.Chrome(service=service, options=options)
            # 最后使用自动管理
            else:
                logging.info("使用自动管理的ChromeDriver")
                driver = webdriver.Chrome(options=options)
        
        elif browser == "firefox":
            # 如果没有传入选项，创建默认选项
            if options is None:
                options = webdriver.FirefoxOptions()
                if HEADLESS:
                    options.add_argument("--headless")
            
            # 尝试使用本地GeckoDriver
            firefox_driver_path = os.path.join(drivers_dir, "geckodriver.exe")
            
            if os.path.exists(firefox_driver_path):
                logging.info(f"使用本地GeckoDriver: {firefox_driver_path}")
                service = FirefoxService(executable_path=firefox_driver_path)
                driver = webdriver.Firefox(service=service, options=options)
            else:
                logging.warning(f"本地GeckoDriver不存在: {firefox_driver_path}，使用自动管理")
                driver = webdriver.Firefox(options=options)
        
        elif browser == "edge":
            # 如果没有传入选项，创建默认选项
            if options is None:
                options = webdriver.EdgeOptions()
                if HEADLESS:
                    options.add_argument("--headless")
                options.add_argument("--start-maximized")
            
            # 尝试使用本地EdgeDriver
            edge_driver_path = os.path.join(drivers_dir, "msedgedriver.exe")
            
            if os.path.exists(edge_driver_path):
                logging.info(f"使用本地EdgeDriver: {edge_driver_path}")
                service = EdgeService(executable_path=edge_driver_path)
                driver = webdriver.Edge(service=service, options=options)
            else:
                logging.warning(f"本地EdgeDriver不存在: {edge_driver_path}，使用自动管理")
                driver = webdriver.Edge(options=options)
        
        else:
            raise Exception(f"不支持的浏览器类型: {browser}")
        
        # 设置隐式等待时间
        if driver:
            driver.implicitly_wait(IMPLICIT_WAIT)
            
        return driver 